<?php
/**
* recdata.php file
* create by ljanson
* @2013-2-3
*/

$data = isset($_POST['data']) ? $_POST['data'] : "";
$ver = isset($_POST['ver']) ? $_POST['ver'] : "";
$verdata0 = md5("~!@#$%^".$data."+_))(*&");
$verdata = md5(md5("~!@#$%^".$data."+_))(*&"));


if(strlen($data) == 0 || strlen($ver) == 0) {
	$msg = (strlen($data) == 0) ? "empty data" : "empty verify";
	exit(json_encode(array("ret"=>0, "msg"=>$msg)));
}

if($ver == $verdata){
	header("Content-Type: text/html; charset=utf-8");
	require_once '../baseClasses/config_ser.php';	
	require_once '../baseClasses/dbConn.php';
	
	$db = new dbConn();
	
	$contents = json_decode($data, true);
	$sql = "";
	$res = -1;
	$UpdateTime = date("Y-m-d H:i:s");
	foreach($contents as $content){
		$content = array_values($content); 
		list($CreateTime, $CurrentPrice, $GoodsId, $GoodsPrice, $OrderNum, $OrderRate, $OrderState) = clean($content);
		$db->sql = "SELECT GoodsId FROM `OrderData` WHERE `GoodsId`={$GoodsId} AND `CreateTime`='{$CreateTime}' AND `OrderNum`={$OrderNum} AND `CurrentPrice`={$CurrentPrice} AND `GoodsPrice`=$GoodsPrice AND `OrderRate`='{$OrderRate}' AND `OrderState`='{$OrderState}' LIMIT 1";
		$result = $db->doResultOne();
		if( ! $result){
			$sql .= "INSERT INTO `OrderData`(`CreateTime`, `CurrentPrice`, `GoodsId`, `GoodsPrice`, `OrderNum`, `OrderRate`, `OrderState`, `UpdateTime`) VALUES('{$CreateTime}', {$CurrentPrice}, '{$GoodsId}', {$GoodsPrice}, '{$OrderNum}', '{$OrderRate}', '{$OrderState}', '{$UpdateTime}');";
		}
		//$sql .= "INSERT INTO `OrderData`(`CreateTime`, `CurrentPrice`, `GoodsId`, `GoodsPrice`, `OrderNum`, `OrderRate`, `OrderState`, `UpdateTime`) VALUES('{$CreateTime}', {$CurrentPrice}, '{$GoodsId}', {$GoodsPrice}, '{$OrderNum}', '{$OrderRate}', '{$OrderState}', '{$UpdateTime}') ON DUPLICATE KEY UPDATE `CreateTime`='{$CreateTime}',`OrderNum`='{$OrderNum}',`CurrentPrice`={$CurrentPrice},`GoodsPrice`=$GoodsPrice,`OrderRate`='{$OrderRate}',`OrderState`='{$OrderState}',`UpdateTime`='{$UpdateTime}';";
	}
	if($sql){
		$db->sql = $sql;
		$res = $db->doExecute();
	}
	switch($res){
		case $res === -1:
			$ret = 4;
			$msg = "data had already existed";
			break;
		case $res === false:
			$ret = 3;
			$msg = "operate fail";
			break;
		case $res === true:
			$ret = 1;
			$msg = "operate success";
			break;
	}
	
	echo json_encode(array("ret"=>$ret, "msg"=>$msg)); 
}
else{
	exit(json_encode(array("ret"=>2, "msg"=>"data verify fail", "GetVer"=>"{$ver}", "GenerateVer1"=>"{$verdata0}", "GenerateVer2"=>"{$verdata}")));
}

function clean($data)
{
	if(empty($data)) return;
		
	if(is_array($data))
	{
		foreach($data as $key=>$value)
		{
			if(is_array($value))
			{
				$clean[$key] = clean($value);
			}
			else
			{
				$clean[$key] = addslashes(htmlspecialchars(trim($value)));
			}
		}
	}
	else 
	{
		$clean = addslashes(htmlspecialchars(trim($data)));
	}
	return $clean;
}
